<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script type="module">
      import MyPromise from "./promise.js";
      // 测试代码
      const promise = new MyPromise((resolve, reject) => {
        setTimeout(() => {
          console.log("执行异步任务");
          // throw 123;
          resolve("成功");
          reject("失败");
        }, 1000);
      });
      promise
        .then(
          (result) => {
            console.log("执行成功：", result); // 输出：成功
            return result;
          },
          (error) => {
            console.error("error:", error); // 不会执行
          }
        )
        .then(
          (result) => {
            console.log("链式调用执行成功：", result); // 输出：成功
          },
          (error) => {
            console.error("error:", error); // 不会执行
          }
        );
      const fetchUser = fetch("http://localhost:3000/api/get/files/1.txt");
      const fetchPosts = fetch("http://localhost:3000/api/get/files/2.txt");
      const fetchComments = fetch("http://localhost:3000/api/get/files/3.txt");

      Promise.all([fetchUser, fetchPosts, fetchComments])
        .then((responses) => {
          console.log("50:", responses);
          return Promise.all(
            responses.map((res) => {
              if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
              return res.text(); // 如果是文本文件使用.text()，如果是JSON则用.json()
            })
          );
        })
        .then((datas) => {
          const [userData, postsData, commentsData] = datas;
          console.log("用户:", userData);
          console.log("帖子:", postsData);
          console.log("评论:", commentsData);
        })
        .catch((error) => {
          console.error("请求失败:", error);
        });
        
      const fetchUser1 = fetch("http://localhost:3000/api/get/files/4.txt");
      const fetchPosts1 = fetch("http://localhost:3000/api/get/files/5.txt");
      const fetchComments1 = fetch("http://localhost:3000/api/get/files/6.txt");
      MyPromise.all([fetchUser1, fetchPosts1, fetchComments1])
        .then((responses) => {
          console.log("所有请求都成功了", responses);
          // 所有请求都成功了
          return MyPromise.all(
            responses.map((res) => {
              res.then((data) => {
                 return data.json();
              })
            })
          );
        })
        .then((data) => {
          console.log("60:所有请求成功:", data);
        })
        .catch((error) => {
          console.error("请求失败:", error);
        });
      function fetchData(url) {
        console.log("106:", url);
        return new MyPromise((resolve, reject) => {
          console.log(typeof XMLHttpRequest);
          // 浏览器环境
          const xhr = new XMLHttpRequest();
          xhr.open("GET", url);
          xhr.onload = () => resolve(xhr.responseText);
          xhr.onerror = () => reject(xhr.statusText);
          xhr.send();

          if (typeof XMLHttpRequest !== "undefined") {
          } else {
            // Node.js 环境
            const https = require("https");
            return new Promise((resolve, reject) => {
              https
                .get(url, (res) => {
                  let data = "";
                  res.on("data", (chunk) => (data += chunk));
                  res.on("end", () => resolve(data));
                })
                .on("error", reject);
            });
          }
        });
      }

      fetchData("http://localhost:3000/api/get/files/1.txt")
        .then((res) => {
          console.log("108:", res);
          return res;
        })
        .then((res) => {
          console.log("110:", res);
        });

      // 并发请求
      function concurRequest(urls, maxNum) {
        return new Promise((resolve, reject) => {
          const results = []; // 存储请求结果的数组
          let count = 0; // 当前正在进行的请求数量
          let nextIndex = 0; // 当前请求的索引
          let completedCount = 0; // 已完成的请求数量
          async function request() {
            if (nextIndex >= urls.length) return resolve(results);
            const i = nextIndex;
            const url = urls[nextIndex++];
            count++;
            try {
              let res = await fetch(url);
              results[i] = res; // 存储请求结果
            } catch (error) {
              results[i] = error; // 存储请求结果
            } finally {
              count--;
              completedCount++;
            }
            if (completedCount === urls.length) {
              resolve(results);
            } else if (nextIndex < urls.length) {
              request();
            }
          }
          while (count < Math.max(urls.length, maxNum)) {
            request();
          }
        });
      }

      // 测试代码
      const urls = [
        "http://localhost:3000/api/get/files/1.txt",
        "http://localhost:3000/api/get/files/2.txt",
        "http://localhost:3000/api/get/files/3.txt",
        "http://localhost:3000/api/get/files/4.txt",
        "http://localhost:3000/api/get/files/5.txt",
        "http://localhost:3000/api/get/files/6.txt",
        "http://localhost:3000/api/get/files/7.txt",
        "http://localhost:3000/api/get/files/8.txt",
        "http://localhost:3000/api/get/files/9.txt",
        "http://localhost:3000/api/get/files/10.txt",
        "http://localhost:3000/api/get/files/11.txt",
        "http://localhost:3000/api/get/files/12.txt",
        "http://localhost:3000/api/get/files/13.txt",
        "http://localhost:3000/api/get/files/14.txt",
        "http://localhost:3000/api/get/files/15.txt",
        "http://localhost:3000/api/get/files/16.txt",
      ];

      concurRequest(urls, 2)
        .then((results) => {
          console.log("所有请求完成:", results);
        })
        .catch((error) => {
          console.error("发生错误:", error);
        });

      for (let i = 0; i < 100; i++) {
        let a = i;
        i++;
        // console.log(a,i);
      }
    </script>
  </body>
</html>
